=begin

This file is part of the arena-ruby-sandbox project, http://arena-ruby-sandbox.googlecode.com

Copyright (c) 2009-2009 Roberto Dario Seminara <robertodarioseminara@gmail.com>

arena-ruby-sandbox is free software: you can redistribute it and/or modify
it under the terms of the gnu general public license as published by
the free software foundation, either version 3 of the license, or
(at your option) any later version.

arena-ruby-sandbox is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.  see the
gnu general public license for more details.

you should have received a copy of the gnu general public license
along with arena-ruby-sandbox.  if not, see <http://www.gnu.org/licenses/>.
=end


module RubySandbox
class ReverseContextSwitcher

	def initialize( sandbox, inner_object )
		@sandbox = sandbox
		@inner_object = inner_object
	end

	def to_s
		self.method_missing("to_s")
	end
	
	def self.inspect
		self.method_missing("inspect")
	end

	def method_missing(m, *args)

		sandbox = @sandbox
		inner_object = @inner_object
		
		
			retval = nil
			sandbox.unprivileged_block do # crear un bloque con privilegios
						# para que el metodo invocado pueda hacer
						# cosas normales sin ninguna restriccion

				if block_given?
					
					args_ = args.map{ |a| sandbox.wrap_in(a) }
					retval = inner_object.send(m,*args_) do |*x|
						sandbox.privileged_block do
							# sacar los privilegios porque el codigo
							# invocado en el yield esta adentro del sandbox
							
							x_ = x.map{ |a| sandbox.wrap_out(a) }
							yield(*x_)
						end
					end

				else
					args_ = args.map{ |a| sandbox.wrap_in(a) }
					retval = inner_object.send(m,*args_)
				end
				
			end
			
			sandbox.wrap_out(retval)
	end

end
end
